const express = require('express');
const app = express();
const http = require('http').createServer(app);
const cors = require('cors');

// 配置 CORS
app.use(cors({
    origin: ['http://localhost:8080', 'http://localhost:5173', 'http://danandgift.free3v.vip'],
    methods: ['GET', 'POST'],
    credentials: true
}));

// 设置静态文件目录
app.use(express.static('public')); // 确保 'public' 是你的静态文件目录

// 默认路由，提供 index.html
app.get('/', (req, res) => {
    res.sendFile(__dirname + '/public/index.html');
});

// Socket.IO 配置
const io = require('socket.io')(http, {
    cors: {
        origin: ['http://localhost:8080', 'http://localhost:5173', 'http://danandgift.free3v.vip'],
        methods: ["GET", "POST"],
        credentials: true,
        allowedHeaders: ["*"]
    }
});

// 跟踪连接的用户数量
let userCount = 0;

// Socket.IO 连接处理
io.on('connection', (socket) => {
    userCount++;
    io.emit('userCount', userCount);
    io.emit('userJoined', `新用户加入！当前在线人数: ${userCount}`);
    console.log('用户已连接，当前在线人数:', userCount);

    socket.on('disconnect', () => {
        userCount--;
        io.emit('userCount', userCount);
        console.log('用户已断开，当前在线人数:', userCount);
    });
});

const PORT = process.env.PORT || 3000;
http.listen(PORT, () => {
    console.log(`服务器运行在端口 ${PORT}`);
});